import * as journalApi from "@/api/journalApi";
import { ResponseCode } from "@/common/Responsetypes";
import { computed, type Ref } from "vue";

import {
  IUploadImgStatus,
  type IUploadImg,
  type IJournalExt,
} from "@/common/JournalTypes";
import { journalUpdated } from "@/bus";

export default function (
  fileList: Ref<IUploadImg[]>,
  journalInfo: IJournalExt
) {
  // true, 所有都上传完了，false，还有没上传完的
  const imgUploadedRef = computed(() => {
    return !fileList.value.some(
      (file) => file.status === IUploadImgStatus.UPLOAD
    );
  });

  async function handleModifyJournal() {
    
    if (journalInfo.content === "") {
      
      uni.showToast({
        title: "内容不能为空",
        icon: "none",
        duration: 2000,
      });
      return;
    }

    if (!imgUploadedRef.value) {
      uni.showToast({
        title: "图片还未上传完",
        icon: "none",
        duration: 2000,
      });
      return;
    }

    journalInfo.photos = fileList.value.map((file) => {
      return {
        url: file.url,
        index: file.index,
        min: file.min,
      };
    });

    uni.showLoading();
    const result = await journalApi.modify({
      ...journalInfo,
    });

    if (result.code === ResponseCode.PASS) {
      uni.hideLoading();
      uni.showToast({
        title: "发布成功",
        icon: "success",
        duration: 2000,
      });

      uni.$emit(journalUpdated, journalInfo);

      uni.navigateBack({
        fail: (e) => {
          console.log(e);
        },
      });
    }
  }

  return {
    handleModifyJournal,
    journalInfo,
    imgUploadedRef,
  };
}
